import tkinter
import webbrowser
from tkinter import ttk, filedialog
import tkinter as tk
import os
import requests
from lxml import etree
from tkinter import messagebox
import re
import datetime
list_music = []
# 版本号
version = "1.3.0"
# 定义请求头
headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36',
    'Cookie':"NMTID=00O0z-9jvyUl1KPmUyBktwnLVgjrU4AAAGT460r2g; _iuqxldmzr_=32; _ntes_nnid=797b07cf746dd80a1cf0f2908e109a69,1734691597858; _ntes_nuid=797b07cf746dd80a1cf0f2908e109a69; WEVNSM=1.0.0; WNMCID=vbrxxg.1734691598921.01.0; WM_TID=N4PI9nlZIJ9EUFFRQUeHTuwK2KIKi4B1; sDeviceId=YD-8a%2FOZ4a2eLpBQ0VAVUbEfDaAmroXiwiC; ntes_utid=tid._.y125TJk6KedEQhAABEPSC%252BkP3aIO%252FmTA._.0; __snaker__id=zR0mxz6BtwNAxQj3; ntes_kaola_ad=1; __csrf=838c094a87efb0274b4c4db693cf5870; MUSIC_U=000B665126F82F6C047EA10DD90907736C9C12593C186A60D353F5867B5FD44A160F1FA72B9ABA18014B591F8C1178F89D8EB765B08033FFF7D3CFEB81E46DF304B947FA783B68301ABD0663D66038B36264FAE338B50923819543CD4D063D0CFCAE455FA0FF4AAEBE77EBA3F11E317E5349D47FD58FAAA54A7907D10EE1DD22DF48B8E0F6639EEBFDBFEF8862A093490C6B5DDBC790DBCB38C121130EAC8EEAD2DAA2F747BC54CCAFA9FD43D18E04AA6E684C49A2C2446F69ECED85792D34646F15BCFF55113BD212B1E4B804867E2901B6DCE9A29FC3BFE587BA6E842CD919589062F6152243AF1BD11405D6ECB634D4BAE32E7E789273964256309FDCE0D92EE51E734542F1DD83F7270C62C33724DA5BC2E1B4B0197B9E1101EACCE67AAF5C84D37B68A34407066883CE0EC5C1DAC3126487774767C802ED8358E68ED1A5D619B9B6B8589EF515F017F0BA3BB7D1A149AE4C306C0E948E64F66D2B63544154; gdxidpyhxdE=Y1NWUrQPfnzYWon8K2ADJB2rhv5cat%5CK1DJTecpjp5f%2FsGlDPiRUCBaeoJSE2PdEt91TxKE%5C3bLRtUu0yulutpuNHDUiV%5CSSVvZIvzXN2ZDRVYK8uT4sDK2emXWTZ%5CxMY%2BStPvI3OBl938%5CkD%2BTZJbQoKyz1R3m1X%2BxTLnJmNrnngWXs%3A1735279647084; WM_NI=may6EOYJyP43no9jwGYWd44FD7TCS2cW6TzQVO38Ar0J0MUjOLF99hbj%2BJ25BIg3ETk4m9FchgacF%2Fa%2FDShqMDWqFab8cifUPkG3CuRg2cFnNOOnG5FVmwnmr3ksqKr1WVo%3D; WM_NIKE=9ca17ae2e6ffcda170e2e6eeadec7b92b29b8fd543f78e8ea3d45e929a9e87d7529299a9ccf752818e97a3b22af0fea7c3b92aafbfb7d7c8459b96b7b1b739aeb1f78bf64d9b89acd5b74e88e99ca4d23aa189fab5f95b9691fdd9c47af49600aed8628d948adabc64a2b6e5abb13f8297a9d4c860a9eca3dac569acb9af84c525a3f18cb4eb7b8f9c9992c56ba2e8ad8ae55f94b589d4c27f92b9fe84c5668e91818fc63f868aa398ed67b2eda594f441b2ef99b7ee37e2a3; JSESSIONID-WYYY=8%2BTn9FXd1gkIjeMs6lIn1C%5CIQCRtJ23hmp7hC3XI%2F7dAd023PMBPfE4Z%2FRjRk5wXOeWhF4Jdu37ZC7mRp2YgBNVDD1qnUq7%5C%2Fyv3bEX8PFf2i%5C%5CV3ZselByWnVEPMNgDsaqVo3%2BNJ88AbW2hY2bOfrTv4q1SHZ4DR6T73iupjIZVpZYV%3A1735452256226"}
# 网页的请求链接
index_url = 'https://music.163.com/discover/toplist?id=3778678'

# 发起网络请求
# response = requests.get(index_url, headers=headers)
response = requests.get(index_url,headers=headers)
# print(response.text)

# 将网页的html字符串转换成树形结构
html = etree.HTML(response.text)

# 使用xpath表达式来筛选出音乐的ID
id_info_list = html.xpath('//ul[@class="f-hide"]/li/a/@href')
# print(id_info_list)

# 使用xpath表达式来筛选出音乐的名称
name_list = html.xpath('//ul[@class="f-hide"]/li/a/text()')
artist_list = html.xpath('//textarea[@id="song-list-pre-data"]/text()')
result = re.findall('"artists":\[(.*?)\]', artist_list[0])
print(result)

singer_list = []
for i in range(0,200):
    singer_list.append(result[i].split('"name":"')[1].split('"')[0])
print(singer_list)
# 判断路径中是否有对应的文件夹, 如果存在则跳过
if not os.path.exists('music'):
    # 如果不存在就创建这个文件夹
    os.mkdir('music')
i = 1
# 使用列表进行遍历
for id_info, name in zip(id_info_list, name_list):


    # 对ID信息使用=进行切割，获取右边的ID数字
    music_id = id_info.split('=')[1]

    # 定义下载音乐的接口链接
    music_url = 'https://music.163.com/song/media/outer/url?id=' + music_id

    # 发起网络请求，获取音乐数据
    # response = requests.get(music_url, headers=headers)

    name = name.replace('/', '-')

    list_music.append(str(i)+'.'+name+"  --"+singer_list[i-1])
    i += 1
    if len(list_music) == 200:
        break
# 获取今天的日期
day = datetime.date.today()
# 将日期格式化为字符串
str_day = str(day)
# 将日期字符串格式化为指定的格式
list_day = str_day.split('-')

window = tk.Tk()

window.title(f"网易云音乐下载  -- by wjh(仅供学习专用)  版本号：{version}")
screenWidth = window.winfo_screenwidth()
screenHeight = window.winfo_screenheight()
# 设置窗口居中
window.geometry(f"500x340+{int((screenWidth-500)/2)}+{int((screenHeight-380)/2)}" )
tab = ttk.Notebook(window)
root = tk.Frame(window)
help = tk.Frame(window)
setting = tk.Frame(window)
tab1 = tab.add(root,text="歌曲榜单")
tab2 = tab.add(setting,text="设置")
tab3 = tab.add(help,text="帮助")

tab.pack(expand=True,fill=tk.BOTH)
label_re = tk.Label(root,text=f"网易云音乐（{list_day[0]}年{list_day[1]}月{list_day[2]}日热歌榜）",font=("黑体",18),fg="#fc3b5b")
label_re.pack()
label_title=tk.Label(root,text="音乐列表",font=("华文彩云",16))
label_title.pack()

show_LB = tkinter.Listbox(root,font=("黑体",10),width=45,justify=tk.CENTER,borderwidth=0,height=10,selectmode=tk.BROWSE)

show_LB.pack()
count=1
# 总页数
page_sum = int(len(list_music)/10)
# 设置标签
def open_file():
    path = rf"{os.getcwd()}\music"
    os.startfile(path)
setting_musicSave = tk.Label(setting,text=f"音乐保存路径",font=("黑体",16))
setting_musicSave.pack(pady=2)
setting_musicSave_path = tk.Label(setting,text=f"{os.getcwd()}\music",font=("黑体",12))
setting_musicSave_path.pack(pady=10)
setting_musicSave_open = tk.Button(setting,text="打开",command=open_file)
setting_musicSave_open.pack()
def checkVersion():
    version_url = "http://whius.top/demo/index.html"
    response_version = requests.get(version_url, headers=headers)
    html_version = etree.HTML(response_version.text)
    version_get = html_version.xpath('//p/text()')[0][0:3]
    if float(version_get) > float(version[0:3]):
        answer = messagebox.askyesno("提示","现在有新版本，是否前往下载？")
        if answer:
            new_version = "http://whius.top/demo/demo.exe"
            webbrowser.open(new_version)
    else:
        messagebox.showinfo("提示","现在没有新版本")

setting_checkVersion = tk.Button(setting,text=f"检查更新",font=("黑体",12),command=checkVersion)
setting_checkVersion.pack(pady=10)
# 帮助标签
label_help = tk.Label(help,text="1.本程序仅供学习使用，请勿用于商业用途\n2.有些歌曲网易云有限制，以我的技术还无法下载，但大多数都可以\n3.此版本为初代版本，后续会不断更新\n4.作者很垃圾,有些bug不会改\n5.作者：巫家浩，此程序仅在联网状态下才能使用",font=("黑体",12))
label_help.pack()

def select():
    index = show_LB.get(show_LB.curselection()).split('.')[0]
    download(int(index))
def download(index):

    response = requests.get(index_url, headers=headers)
    id_info_list = html.xpath('//ul[@class="f-hide"]/li/a/@href')
    if not os.path.exists('music'):
        # 如果不存在就创建这个文件夹
        os.mkdir('music')
    music_id = id_info_list[index-1].split('=')[1]
    music_url = 'https://music.163.com/song/media/outer/url?id=' + music_id
    # 发送请求
    response = requests.get(music_url, headers=headers)

    with open('music/' + list_music[index-1] +'.mp3', mode='wb') as f:
        f.write(response.content)
    # 判断文件大小是否为102651字节 若是则删除
    # 判断文件是否下载成功
    if os.path.getsize('music/' + list_music[index-1] +'.mp3') == 102651:
        messagebox.showinfo('提示',"下载失败！\n部分歌曲因未找到地址暂时无法下载！")
        os.remove('music/' + list_music[index-1] +'.mp3')
        return
    else:
        messagebox.showinfo('提示',"下载成功！\n已保存至："+os.getcwd()+"\music")
    print(list_music[index-1])

def nextpage():
    global count
    count += 1
    a = show_LB.get(9).split('.')[0]
    a = int(a)
    label_count["text"]=f"{count}/{page_sum}"
    if count>page_sum:
        count = 20
        label_count["text"] = f"{count}/{page_sum}"
    if a>=200:
        for a in range(190, 200):
            show_LB.insert("end", list_music[a])
    else:
        show_LB.delete(0,tk.END)
        for a in range(a,a+10):
            show_LB.insert("end",list_music[a])
def lastpage():
    global count
    count -= 1
    a = show_LB.get(0).split('.')[0]
    a = int(a)
    label_count["text"] = f"{count}/{page_sum}"
    if count<1:
        count = 1
        label_count["text"] = f"{count}/{page_sum}"
    if a-11 < 0:
        for a in range(0, 9):
            show_LB.insert("end", list_music[a])
    else:
        show_LB.delete(0,tk.END)
        for a in range(a - 11, a):
            show_LB.insert("end", list_music[a])
button_Label = tkinter.Frame(root)
button_Label.pack()

button_lastpage = tkinter.Button(button_Label,text="上页",font=("黑体",12),fg="#fca60b",relief="flat",command=lastpage)
button_lastpage.grid(row=0,column=0,padx=20,pady=10)
label_count = tkinter.Label(button_Label,text=f"1/{page_sum}",font=("黑体",12))
label_count.grid(row=0,column=1,padx=20,pady=10)
button_nextpage = tkinter.Button(button_Label,text="下页",font=("黑体",12),fg="#fca60b",relief="flat",command=nextpage)
button_nextpage.grid(row=0,column=12,padx=20,pady=10)
button_download = tkinter.Button(root,text="下载",relief="flat",font =("黑体",12),bg="#fc3d49",fg="white",command=select)
button_download.pack()
for item in list_music:
    show_LB.insert("end",item)

window.mainloop()